package com.wangcanxuan.www.util.pool;

import com.wangcanxuan.www.util.ConnectionPoolUtil;

import java.sql.Connection;

/**
 * 对连接的一个封装，除了提供基本的连接，还可以记录这个连接的时间，如果有的连接一直连接不释放
 * 那么可以通过查看已连接时间来判断是否超时，超时了将主动释放这个连接或者返回到空闲连接池。
 *
 * @author HHLJ
 * @date 2022/03/20
 */
public class PooledConnection implements AutoCloseable{

    /**
     * 真实连接
     */
    public Connection connection;

    /**
     * 是否在连接
     */
    private boolean isBusy = false;

    /**
     * 连接已用时间
     */
    private Long checkOutTime;

    /**
     * 连接的hashCode
     */
    private final int hashCode;

    public PooledConnection(Connection connection) {
        this.connection = connection;
        this.hashCode = connection.hashCode();
        this.checkOutTime = System.currentTimeMillis();
    }

    public Long getCheckOutTime() {
        return checkOutTime;
    }

    public void setCheckOutTime(Long checkOutTime) {
        this.checkOutTime = checkOutTime;
    }

    /**
     * 判断两个连接内其connection的hashCode是否一样
     *
     * @param connection 连接
     * @return boolean
     */
    public boolean equals(Connection connection) {
        return hashCode() == connection.hashCode();
    }

    @Override
    public int hashCode() {
        return hashCode;
    }

    public boolean getIsBusy() {
        return isBusy;
    }

    public void setIsBusy(boolean busy) {
        isBusy = busy;
    }

    @Override
    public void close() throws Exception {
        ConnectionPoolUtil.getInstance().release(this.connection);
    }
}
